package cn.jhc.teachingquality.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.android.volley.toolbox.RequestFuture;

import java.util.List;
import java.util.concurrent.ExecutionException;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.jhc.teachingquality.Global;
import cn.jhc.teachingquality.R;
import cn.jhc.teachingquality.adapter.ListTeachingLogAdapter;
import cn.jhc.teachingquality.bean.TeachingLog;
import cn.jhc.teachingquality.net.RequestQueueFactory;
import cn.jhc.teachingquality.net.teaching.ListCheckedTeachingLogsRequest;
import cn.jhc.teachingquality.rx.RxBus;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by luyanfei on 16-4-9.
 */
public class TeachingLogListFragment extends Fragment{

    @InjectView(R.id.list_teaching_log_swipe_container)
    SwipeRefreshLayout swipeRefreshLayout;

    @InjectView(R.id.list_teaching_log_view)
    RecyclerView recyclerView;

    private ListTeachingLogAdapter listTeachingLogAdapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.list_teaching_log_fragment, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ButterKnife.inject(this, view);

        recyclerView.setLayoutManager(new LinearLayoutManager(view.getContext()));
        listTeachingLogAdapter = new ListTeachingLogAdapter();
        recyclerView.setAdapter(listTeachingLogAdapter);
        recyclerView.setVisibility(View.GONE);

        swipeRefreshLayout.setEnabled(false);
        swipeRefreshLayout.setRefreshing(false);

        refreshList();

        //监听TeachingLogList刷新事件
        RxBus.getInstance().take(String.class)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new Func1<String, Boolean>() {
                    @Override
                    public Boolean call(String s) {
                        return s.equals(Global.EVENT_REFRESH_TEACHING_LOG_LIST);
                    }
                })
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        refreshList();
                    }
                });
    }

    public void refreshList() {
        getTeachingLogs().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<TeachingLog>>() {
                    @Override
                    public void onCompleted() {
                        Toast.makeText(getContext(), "教学日志加载完成", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(getContext(), "教学日志加载出错。", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNext(List<TeachingLog> teachingLogs) {
                        recyclerView.setVisibility(View.VISIBLE);
                        listTeachingLogAdapter.addTeachingLogs(teachingLogs);
                    }
                });
    }

    private Observable<List<TeachingLog>> getTeachingLogs(){
        return Observable.defer(new Func0<Observable<List<TeachingLog>>>() {
            @Override
            public Observable<List<TeachingLog>> call() {
                try {
                    return Observable.just(fetchTeachingLogs());
                } catch (ExecutionException | InterruptedException e) {
                    Log.e(Global.LOG_TAG, e.getMessage());
                    return Observable.error(e);
                }
            }
        });
    }

    private List<TeachingLog> fetchTeachingLogs() throws ExecutionException, InterruptedException {
        RequestFuture<List<TeachingLog>> future = RequestFuture.newFuture();
        ListCheckedTeachingLogsRequest request = new ListCheckedTeachingLogsRequest(future);
        RequestQueueFactory.getRequestQueue(getContext()).add(request);
        return future.get();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }
}
